package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"image/color"
)

// Label 自定义 Label 结构
type Label struct {
	*widget.Label
	border2 *canvas.Rectangle
}

// NewLabel 创建一个带有边框的自定义 Label
func NewLabel(name string) *Label {
	label := &Label{
		Label: widget.NewLabel(name),
		border2: &canvas.Rectangle{
			FillColor:   color.Transparent,
			StrokeColor: color.RGBA{0, 0, 0, 255}, //黑
			StrokeWidth: 2,
		},
	}
	label.ExtendBaseWidget(label) // 扩展基础 Widget
	return label
}

// CreateRenderer 实现自定义渲染器
func (l *Label) CreateRenderer() fyne.WidgetRenderer {

	//这个是不支持的写法  border := canvas.NewRectangle(color.RGBA{255, 0, 0, 255}) //  边框
	//border.StrokeWidth = 2                                  // 边框宽度
	//border.FillColor = color.Transparent                    // 透明填充
	return &customRenderer{
		objects: []fyne.CanvasObject{l.Label, l.border2},
		border: &canvas.Rectangle{
			FillColor:   color.Transparent,
			StrokeColor: color.RGBA{255, 0, 0, 255},
			StrokeWidth: 2,
		},
	}
}

// 自定义渲染器
type customRenderer struct {
	objects []fyne.CanvasObject
	border  *canvas.Rectangle
}

// Layout 实现布局方法
func (r *customRenderer) Layout(size fyne.Size) {
	// 计算边框和标签的大小
	r.objects[0].Resize(size) // 设置边框大小
	r.objects[1].Resize(fyne.NewSize(size.Width/2, size.Height/2))
	r.objects[1].Move(fyne.NewPos(0, 0)) // 确保边框位置与图像一致
	r.border.Resize(size)
	r.border.Move(fyne.NewPos(0, 0)) // 确保边框位置与图像一致
}

// MinSize 返回最小大小
func (r *customRenderer) MinSize() fyne.Size {
	return fyne.NewSize(0, 0) // r.objects[0].MinSize()
}

// Refresh 刷新渲染器
func (r *customRenderer) Refresh() {
	for _, obj := range r.objects {
		obj.Refresh()
	}
	r.border.Refresh() // 刷新边框
}

// Objects 返回渲染对象
func (r *customRenderer) Objects() []fyne.CanvasObject {
	// 这个添加顺序决定渲染的层次层级
	objects := []fyne.CanvasObject{}
	objects = append(objects, r.border)
	objects = append(objects, r.objects...)
	return objects
}

// Destroy 清理渲染器
func (r *customRenderer) Destroy() {
	// 可以在这里清理资源
}

func main() {
	myApp := app.New()
	mainWindow := myApp.NewWindow("带边框的标签")

	label := NewLabel("Hello, Fyne!")

	mainWindow.SetContent(container.NewVBox(label))
	mainWindow.Resize(fyne.NewSize(300, 200))
	mainWindow.ShowAndRun()
}
